<template>
  <v-container class="py-10">
    <v-row justify="center">
      <v-col cols="12" md="8">
        <v-card class="pa-6 rounded-xl elevation-4">
          <v-row>
            <!-- 左侧：头像上传 -->
            <v-col cols="12" md="4" class="text-center">
              <!-- 当前头像或预览图 -->
              <v-avatar size="120" class="mb-4 mx-auto">
                <v-img :src="avatarPreview || user.avatar" />
              </v-avatar>

              <!-- 选择新头像文件 -->
              <v-file-input
                label="选择头像"
                accept="image/*"
                prepend-icon="mdi-camera"
                @update:modelValue="handleAvatarSelection"
                outlined
                dense
              />

              <!-- 确认上传按钮（仅在选择了文件时显示） -->
              <v-btn color="primary" class="mt-2" @click="uploadAvatar" v-if="selectedAvatarFile">
                确认上传
              </v-btn>
            </v-col>

            <v-spacer />

            <!-- 右侧：个人信息 -->
            <v-col cols="12" md="8">
              <v-form ref="formRef" @submit.prevent="submitProfile" v-model="valid">
                <v-text-field v-model="user.username" label="用户名" required outlined />

                <v-text-field
                  v-model="user.email"
                  label="邮箱"
                  :rules="emailRules"
                  required
                  outlined
                />

                <v-text-field
                  v-model="user.password"
                  label="新密码（留空表示不修改）"
                  :rules="passwordRules"
                  type="password"
                  outlined
                />

                <v-btn type="submit" color="primary" class="mt-4" :disabled="!valid">
                  保存信息
                </v-btn>
              </v-form>
            </v-col>
          </v-row>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { IUploadAvatar, me, updateUserInfo } from '@/api/users.js'
import { useUserStore } from '@/stores/userStore.js'
import { useMessageStore } from '@/stores/MessageStore.js'
import router from '@/router/index.js'

const formRef = ref(null)
const valid = ref(false)

const user = ref({
  username: '',
  email: '',
  password: '',
  avatar: '',
})

const userStore = useUserStore()

const emailRules = [(v) => !!v || '邮箱不能为空', (v) => /.+@.+\..+/.test(v) || '邮箱格式不正确']

const passwordRules = [(v) => !v || v.length >= 6 || '密码至少6位']

onMounted(async () => {
  try {
    const { data } = await me()
    user.value = {
      ...data,
      password: '',
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
  }
})

const selectedAvatarFile = ref(null)
const avatarPreview = ref(null)

function handleAvatarSelection(file) {
  if (file) {
    selectedAvatarFile.value = file
    avatarPreview.value = URL.createObjectURL(file)
  } else {
    selectedAvatarFile.value = null
    avatarPreview.value = null
  }
}

async function uploadAvatar() {
  if (!selectedAvatarFile.value) return

  const formData = new FormData()
  formData.append('avatar', selectedAvatarFile.value)

  try {
    await IUploadAvatar(formData)
    selectedAvatarFile.value = null
    useMessageStore().trigger('更新成功', 'success')
  } catch (err) {
    console.error('上传失败:', err)
    useMessageStore().trigger('更新失败', 'error')
  } finally {
    await updateInfo()
  }
}

// 修改邮箱、密码（单独接口）
async function submitProfile() {
  if (!formRef.value?.validate()) return

  const data = { username: user.value.username, email: user.value.email }
  if (user.value.password) {
    data.password = user.value.password
  }

  try {
    await updateUserInfo(data)
    useMessageStore().trigger('信息更新成功，请重新登录！', 'success')
    router.push('/login')
  } catch (err) {
    console.error('更新失败:', err)
    useMessageStore().trigger('更新失败', 'error')
  } finally {
    await updateInfo()
  }
}

const updateInfo = async () => {
  const { data } = await me()
  const { username, email, avatar } = data
  userStore.updateUserInfo({ username, email, avatar })
}
</script>
